from django.shortcuts import HttpResponseRedirect
from cmdb.util import time
from cmdb.models import UserToken
from django.conf import settings
from cmdb.security import PyCrypto
from cmdb.api.session import session_get
from cmdb.api.session import session_set
from time import sleep

try:
    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object


white_path = [
    '/login',
    '/login_action',
    '/api/user/login',
    '/api/pk',
]
white_path_part = [
    '/admin',
    '/websocket',
    '/api/error/',
]

class MiddleWare(MiddlewareMixin):

    @staticmethod
    def process_request(req):

        # print('------', req.path, '------')

        # 过滤白名单中的请求网址
        for wpp in white_path_part:
            if req.path.__contains__(wpp):
                # print('pass-1')
                return process_request_next(req)

        for wp in white_path:
            if req.path == wp:
                # print('pass-2')
                return process_request_next(req)

        # 检测token 是否存在
        token = req.POST.get('token', None)
        if not token:
            token = req.GET.get('token', None)
        if not token:
            return HttpResponseRedirect('/api/error/token_is_null')

        # 检测token是否有效
        if not check_token(req, token):

            if req.META.get('HTTP_FROM', 'client') == 'browser':
                # print('browser')
                return HttpResponseRedirect('/login')
            else:
                # print('client')
                return HttpResponseRedirect('/api/error/no_certification')

        else:
            return process_request_next(req)





def process_request_next(req):
    # 解密从客户端传递过来的参数
    enc_data = req.POST.get('enc_data', None)
    token = req.POST.get('token', None)



    # 暂时屏蔽, 不加密
    # print('enc_data', enc_data)
    # if enc_data:
    #     key = session_get(token, 'key')
    #     print('key', key)
    #     crypt = PyCrypto(key)
    #     dec_data = crypt.decrypt(enc_data)
    #     session_set(token, 'data', dec_data)

    pre_data = session_get(token, 'data')
    while True:
        if pre_data:
            sleep(0.2)
        else:
            break
    session_set(token, 'data', enc_data)


    param_str = enc_data
    if not param_str:
        param_str = ''
    pre_path = req.path + '?' + param_str
    session_set(token, 'pre_path', pre_path)


def check_token(req, token):

    last_time = session_get(token, 'last_time')
    pre_path = session_get(token, 'pre_path')
    if pre_path == req.path:
        if last_time != 0 and last_time + settings.OPERATION_DURATION > time.current_timestamp():
            print('操作太频繁了')
            return False

    session_set(token, 'last_time', time.current_timestamp())


    if not session_get(token, 'user_id'):
        return False

    # 使用密钥加密时需要检测是否存在协商好的密钥
    if not session_get(token, 'key'):
        return False

    return True



